﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Collections;
using System.Collections.ObjectModel;
using System.Data.Services.Client;
using System.Diagnostics;
using DailyBread.Helpers;

namespace DailyBread.Views
{
    public partial class MyAmens : PhoneApplicationPage
    {
        ObservableCollection<DailyVerse> verseList = new ObservableCollection<DailyVerse>();
        ListBoxItem contextListBoxItem;

        public MyAmens()
        {
            InitializeComponent();

            BreadCache<DateTime, DailyVerse> amenCollection = IsolatedStorageHelper.GetObject<BreadCache<DateTime, DailyVerse>>("CachedBread");

            if (amenCollection != null)
            {
                foreach(var key in amenCollection.entries.Keys)
                {
                    if (amenCollection.entries[key].personalFav)
                    {
                        verseList.Add(amenCollection.entries[key]);
                    }
                }                
            }
            AmenList.ItemsSource = verseList;

        }

        private void TextBlockBreadName_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            DailyVerse verseSelection = (sender as TextBlock).DataContext as DailyVerse;

            Util.AddToLog("FavClick");

            ((App)Application.Current).context.currentDisplayDate = verseSelection.breadDate;
            //((App)Application.Current).useToday = false;          
            this.NavigationService.GoBack();
        }



        private void TextBlockBreadName_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            Point tmpPoint = e.GetPosition(null);
            contextListBoxItem = null;
            List<UIElement> oControls = (List<UIElement>)VisualTreeHelper.FindElementsInHostCoordinates(tmpPoint, this);
            foreach (UIElement ctrl in oControls)
            {
                if (ctrl is ListBoxItem)
                {
                    contextListBoxItem = (ListBoxItem)ctrl;
                    break;
                }

            }
        }

        private void ContextMenuDelete_Click(object sender, RoutedEventArgs e)
        {
            DailyVerse dv = contextListBoxItem.Content as DailyVerse;
            int index = verseList.IndexOf(dv);
            verseList.RemoveAt(index);
            Util.AddToLog("FavDelete");

            try
            {
                Util.RemoveAmen(dv);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());
            }
        }
    }
}